package spring.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import spring.Spitter;
import spring.services.SpitterRepo;

import javax.validation.Valid;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * Created by kassadin@foxmail.com on 2017/4/27 0027.
 */
@Controller
@RequestMapping("/spitter")
public class SpitterController {

    private SpitterRepo spitterRepo;

    @Autowired
    public SpitterController(SpitterRepo spitterRepo) {
        this.spitterRepo = spitterRepo;
    }

    @RequestMapping(value = "/register",method = GET)
    public String showRegForm() {
        return "registerForm";
    }

    @RequestMapping(value = "register", method = POST)
    public String processReg(@Valid Spitter spitter, Errors errors) {
        if (errors.hasErrors()) {
            System.out.println(errors.getFieldError().getDefaultMessage());
            return "registerForm";
        }
        Spitter saved = spitterRepo.save(spitter);
        return "redirect:/spitter/" + spitter.getUsername();
    }

    @RequestMapping("/{username}")
    public String showSpitterProfile(@PathVariable  String username, Model model) {
        Spitter spitter = spitterRepo.findByUsername(username);
        model.addAttribute(spitter);
        return "profile";
    }
}
